/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in Pw
*@des: seesion管理器
*@name: seesion_manager.cpp
*@author: zhognsx
*@time: 2015-11-16
*********************************************************/

#include "session_manager.h"

session_manager::session_manager(boost::asio::io_service& io_srv, int expires_time)
	:m_io_srv(io_srv), m_check_tick(io_srv), m_expires_time(expires_time)
{
	check_connection();

}

session_manager::~session_manager()
{
	//writeLock lock(m_mutex);
	//m_check_tick.cancel();
	std::cout << "session_manager  delete" << std::endl;
}

//检查服务器所有session的连接状态  
void session_manager::check_connection()
{
	writeLock lock(m_mutex);
	session_set::iterator iter = m_sessions.begin();
	while (iter != m_sessions.end())
	{
		//先执行断开操作，然后执行删除操作
		if (!iter->session->socket().is_open()) //已断开，删除已断开的连接  
		{
			//iter->session->async_close();
			iter = m_sessions.erase(iter);
			continue;
		}
		else{
			if (iter->session->is_timeout())  //如果session已长时间没操作，则关闭  
			{
				iter->session->async_close();//通过关闭触发删除session 
			}
		}
		++iter;
	}
	
	m_check_tick.expires_from_now(boost::posix_time::seconds(m_expires_time));
	m_check_tick.async_wait(boost::bind(&session_manager::check_connection, this));
}

void session_manager::add_session(session_ptr p)
{
	writeLock lock(m_mutex);
	session_stu stuSession;
	stuSession.id = p->get_id();
	stuSession.address = p->get_addr_ip();
	stuSession.session = p;
	m_sessions.insert(stuSession);
}
